package com.wjs.zpro.controller;

import com.wjs.zpro.entity.UserEntity;
import com.wjs.zpro.service.impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/user/register")
public class UserRegisterController extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //TODO : 实现用户注册逻辑
        System.out.println("用户注册------------");


        //获取用户数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String confirmPwd = req.getParameter("confirm-password");

        System.out.println("收到用户注册数据：" + username + "--" + password + "--" + email + "--" + confirmPwd);

        //数据校验
        // 用户名：6位以上的字母数字组合
        String usernamePattern = "^[a-zA-Z0-9]{6,}$";

        // 密码：6位以上的字母数字组合
        String passwordPattern = "^[a-zA-Z0-9]{6,}$";

        // 邮箱：合法的邮箱格式
        String emailPattern = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";

        if (!username.matches(usernamePattern)) {
            gotoRegesterPage(req, resp, "用户名格式错误，请重新输入");
            return;
        }
        if (!password.matches(passwordPattern)) {
            gotoRegesterPage(req, resp,"密码格式错误，请重新输入");
            return;
        }
        if (!email.matches(emailPattern)) {
            gotoRegesterPage(req, resp,"邮箱格式错误，请重新输入");
            return;
        }
        // 确认密码：与密码一致（直接比较，无需正则）
        if (!confirmPwd.equals(password)) {
            gotoRegesterPage(req, resp,"确认密码不一致，请重新输入");
            return;
        }
        System.out.println("数据校验合法性通过------");

        //把用户信息保存到JavaBean中,方便传参
        UserServiceImpl userService = new UserServiceImpl();

        //调用注册方法
        UserEntity user = new UserEntity();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);

        //甩锅式代码，甩给service层
        try {
            userService.register(user);
            //跳转页面
            //编码

            //带数据办法1：重定向去登录页
            //把要带的数据给URL后面追加K=V参数
            //问题：中文需要编码才能带；页面取值比较复杂
            //编码
//            String msg =URLEncodeUtil.encode（"注册成功，请登录"）;
//            resp.sendRedirect("/zpro/Login.jsp?msg="+msg);
            //带数据办法2：给请求域中设置一个属性，告诉用户注册成功
            //注意：页面相对路问题；页面如果以后都用/项目名/资源路径放心用
//            req.setAttribute（"msg"，"注册成功，请登录"）;
//            req.getRequestDispatcher("/Login.jsp").forward(req,resp) ;
            //带数据办法3：给域中放数据，重定向获取，用session
            //页面取值直接${}
            //弊端:session中的提示消息一直存在
            HttpSession session = req.getSession();
            session.setAttribute("msg", "注册成功，请登录");
            resp.sendRedirect("/zpro/login.jsp");
        }catch (SQLException e){
            gotoRegesterPage(req, resp, "用户名或邮箱已经存在，请重新输入");
        } catch (Exception e) {
            gotoRegesterPage(req, resp, "系统异常，请稍后再试");

        }


    }

    private static void gotoRegesterPage(HttpServletRequest req, HttpServletResponse resp,String msg) throws ServletException, IOException {
        req.setAttribute("msg",msg);
        req.getRequestDispatcher("/register.jsp").forward(req, resp);
    }

}
